"""
|===== Conference Bot Plugin ============
|= Admin Commands
|===== By: ==============================
|= Patrick Kennedy
|===== Current Version: =================
|= 1.0
|===== Description: =========================================
|= Admin only commands.
|===== Additional Comments: =================================
|= 
|============================================================"""

import os
import traceback

from utils import debug, readall, readcore

global pluglog
pluglog = file(os.path.join("errors","PluginError.log"), "a+")

def cmd_reload(bot,user,args):
	"""Reload parts of the bot.
	Useage: Reload [conf | plugins | all]
	bot - Reloads all the bot's .ini files.
	plugins - reloads all the bots plugins.
	all/blank - reloads both options."""
	
	if args in ["conf","bot","ini","all", ""]:
		readall()
		readcore(bot)
		bot.msg(user,"Bot config reloaded.")
		debug(2,"All bot .ini files have been reloaded.")
		
	if args in ["plugin", "plugins", "all", ""]:
		loaded = []
		for i in bot.config.system.plugins.split(" "):
			try:
				a = open(os.path.join("plugins","plugin_%s.py") % i,"r").read()
				if bot.pluginhash[i] == hash(a):
					continue
				plugin = {}
				exec a in plugin
				plugin["init"](bot)
				bot.pluginhash[i] = hash(a)
				loaded.append(i)
			except IOError:
				bot.error(user,'The plugin "plugin_%s.py" could not be found.' % args)
				continue
			except:
				traceback.print_exc()
				print >>pluglog, "\n"
				traceback.print_exc(None, pluglog)
				pluglog.close()
				bot.error(user, 'There was an error importing the plugin. A report has been logged.')
				continue
		
		if loaded == []:
			loaded.append("None to be refreshed.")
		bot.msg(user,"Plugins loaded: " + " ".join(loaded))
		debug(2,"All bot plugins have been reloaded.")
	
def cmd_loadplugin(bot,user,args):
	"""Load a new plugin.
	Usage: loadplugin <new plugin>
	 This will load a new plugin, which will be instantly ready for use."""
			
	if args in bot.config.system.plugins.split(" "):
		bot.error(user,"This plugin has already been loaded. To update it please use ')reload plugins'")
		
	else:
		try:
			a = open(os.path.join("plugins","plugin_%s.py") % args,"r").read()
			plugin = {}
			exec a in plugin
			plugin["init"](bot)
			bot.msg(user, "Loaded plugin: " + args)
			bot.config.system.plugins += " " + args
			bot.config.save()
		except IOError:
			bot.error(user,'The plugin "plugin_%s.py" could not be found.' % args)
		except:
			traceback.print_exc()
			print >>pluglog, "\n"
			traceback.print_exc(None, pluglog)
			pluglog.close()
			bot.error(user, 'There was an error importing the plugin. A report has been logged.')
			
def cmd_view(bot, user, args):
	"""View a user's variables.
	Usage: /view <displayname>"""
	jid = getjid(args.split(' ',1)[0])
			
def cmd_addmod(bot, user, args):
	"""Add a new moderator.
	Usage: /addmod <displayname>"""
	
	jid = getjid(args.split(' ',1)[0])
	if bot.getJidStatus(jid).items() != []:
		addmod(jid)
		bot.msg(user, "%s is now a moderator." % getdisplayname(jid))
		bot.msg(jid, "%s has made you a moderator." % getdisplayname(user))
	else:
		bot.msg(user, "That user doesn't exist. Please check the name.")
		
def cmd_delmod(bot, user, args):
	"""Remove a moderator.
	Usage: /delmod <displayname>"""
	
	jid = getjid(args.split(' ',1)[0])
	if bot.getJidStatus(jid).items() != []:
		delmod(jid)
		bot.msg(user, "%s is no longer a moderator." % getdisplayname(jid))
		bot.msg(jid, "%s has removed your mod-ship." % getdisplayname(user))
	else:
		bot.msg(user, "That user doesn't exist. Please check the name.")
			
def init(bot):
	bot.addAdminCommand("reload",cmd_reload)
	bot.addAdminCommand("loadplugin",cmd_loadplugin)
	bot.addAdminCommand("addmod", cmd_addmod)
	bot.addAdminCommand("delmod", cmd_delmod)
